using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Models;

namespace Data
{
    /// <summary>
    /// 应用程序数据库上下文，继承自Identity框架的DbContext
    /// </summary>
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        /// <summary>
        /// 构造函数，配置数据库上下文选项
        /// </summary>
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        /// <summary>
        /// 应用用户表
        /// </summary>
        public DbSet<User> AppUsers { get; set; }

        /// <summary>
        /// 应用角色表
        /// </summary>
        public DbSet<Role> AppRoles { get; set; }

        /// <summary>
        /// 权限表
        /// </summary>
        public DbSet<Permission> Permissions { get; set; }

        /// <summary>
        /// 用户角色关联表（覆盖Identity默认的UserRoles）
        /// </summary>
        public new DbSet<UserRole> UserRoles { get; set; }

        /// <summary>
        /// 角色权限关联表
        /// </summary>
        public DbSet<RolePermission> RolePermissions { get; set; }

        /// <summary>
        /// 刷新令牌表
        /// </summary>
        public DbSet<RefreshToken> RefreshTokens { get; set; }

        /// <summary>
        /// 配置实体关系和数据库模型
        /// </summary>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // 调用基类的OnModelCreating方法，配置Identity相关的表
            base.OnModelCreating(modelBuilder);

            // 避免与Identity的Users表冲突，重命名表
            modelBuilder.Entity<User>().ToTable("AppUsers");
            modelBuilder.Entity<Role>().ToTable("AppRoles");

            // 配置用户-角色多对多关系
            modelBuilder.Entity<UserRole>()
                .HasOne(ur => ur.User)
                .WithMany(u => u.UserRoles)
                .HasForeignKey(ur => ur.UserId);

            modelBuilder.Entity<UserRole>()
                .HasOne(ur => ur.Role)
                .WithMany(r => r.UserRoles)
                .HasForeignKey(ur => ur.RoleId);

            // 配置角色-权限多对多关系
            modelBuilder.Entity<RolePermission>()
                .HasOne(rp => rp.Role)
                .WithMany(r => r.RolePermissions)
                .HasForeignKey(rp => rp.RoleId);

            modelBuilder.Entity<RolePermission>()
                .HasOne(rp => rp.Permission)
                .WithMany(p => p.RolePermissions)
                .HasForeignKey(rp => rp.PermissionId);

            // 配置刷新令牌与用户的一对多关系
            modelBuilder.Entity<RefreshToken>()
                .HasOne(rt => rt.User)
                .WithMany()
                .HasForeignKey(rt => rt.UserId)
                .OnDelete(DeleteBehavior.Cascade);
        }
    }
} 